package xpn.platform.modules.sys.org;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler;
import org.springframework.data.rest.webmvc.RepositoryRestController;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import xpn.platform.common.config.XpnPlatformConfig;
import xpn.platform.common.repository.XpnRepositoryController;
import xpn.platform.modules.sys.user.SysUser;
import xpn.platform.modules.sys.user.SysUserDAO;

import com.google.common.base.Strings;

@RepositoryRestController
@ResponseBody
@RequestMapping("orgs")
public class SysOrgController extends XpnRepositoryController<SysOrg, Long> {

    @SuppressWarnings("rawtypes")
    @Autowired
    private PagedResourcesAssembler pagedResourcesAssembler;

    @Autowired
    SysOrgService orgService;

    @Autowired
    XpnPlatformConfig xpnPlatformConfig;

    @Autowired
    SysOrgDAO orgDao;

    @Autowired
    SysUserDAO userDao;

    /*
     * 根据指定的角色条件和ou条件查找选人发送的机构列表。
     *
     * @see SysOrgService
     */
    @SuppressWarnings("unchecked")
    @GetMapping("search/sendeeselect")
    public Object findSendeeSelectOrgs(@RequestParam(value = "roleCondition", required = false) String roleCondition,
                                       @RequestParam(value = "ouLevel", required = false) String paramOuLevel,
                                       @RequestParam(value = "ouType", required = false) String paramOuType,
                                       @RequestParam(value = "starterId", required = false) String starterId,
                                       @RequestParam(value = "mySenderId", required = false) String mySenderId,
                                       @RequestParam(value = "specifiedUsersHref", required = false) String specifiedUsersHref,
                                       PersistentEntityResourceAssembler resourceAssembler, HttpServletRequest request) {

        // 参数转换
        Integer ouLevel = -1;
        if (!Strings.isNullOrEmpty(paramOuLevel)) {
            ouLevel = Integer.parseInt(paramOuLevel);
        }

        Integer ouType = -1;
        if (!Strings.isNullOrEmpty(paramOuType)) {
            ouType = Integer.parseInt(paramOuType);
        }
        String xpnTokenName = xpnPlatformConfig.getSecurity().getAuthenticationTokenName();
        String token = request.getHeader(xpnTokenName);
        // 调用服务获取机构列表
        List<SysOrg> orgList = orgService.findSendeeSelectOrgs(roleCondition, ouLevel, ouType,starterId,mySenderId,specifiedUsersHref,xpnTokenName,token);
		List<Sort.Order> orders = new ArrayList<>();
		orders.add(new Sort.Order(Sort.Direction.DESC,"id"));
		Pageable pageable = PageRequest.of(0, 1000, Sort.by(orders));
        Page<SysOrg> page = new PageImpl<>(orgService.getSafeOrgListForRestConvert(orgList), pageable,
                orgList.size());
        return pagedResourcesAssembler.toModel(page, resourceAssembler);
    }

    /*
     * 获取树形组织机构人员
     */
    @SuppressWarnings("unchecked")
    @GetMapping("search/getTreeOrgUser")
    public Map<String,Object> getTreeOrgUser(){
    	List<Map<String,Object>> list = new ArrayList<>();
    	String jpql = "From SysUser su WHERE su.org != '' Order BY su.org ASC ";
    	List<SysUser> users = userDao.filterByJpql(jpql);
    	int level = 0;
    	Map<String,Object> map = new HashMap<>();
    	Map<String,Object> map2 = new HashMap<>();
    	Map<String,Object> map3 = new HashMap<>();
    	String orgIds = "";
    	List<SysOrg> orgs = orgDao.findByParentOrgIsNull();
    	for (SysOrg org : orgs) {
    		orgIds+="org_"+org.getId()+"#";
    		map = new HashMap<>();
    		map.put("id", "org_"+org.getId()+"");
    		map.put("text", org.getOrgName());
    		map.put("sortNo", org.getSortNo());
    		map.put("isLeaf", false);
    		map.put("parentId", null);
    		list.add(map);
    		String service = xpnPlatformConfig.getUser().getService();
    		for(SysUser user:users){
    			map2 = new HashMap<>();
    			map3 = new HashMap<>();
    			String fetchOrgName = user.fetchOrgFullName();
    			level = fetchOrgName.split("/").length;
        		if(org.getId().toString().equals(user.getOrg().fetchAncestorId()+"")){
    				SysOrg o = user.getOrg();
        			if(level==2){
        				if(orgIds.indexOf(o.getId()+"#")==-1){
        					orgIds+="org_"+o.getId()+"#";
        					map = new HashMap<>();
            	    		map.put("id", "org_"+o.getId()+"");
            	    		map.put("text", o.getOrgName());
            	    		map.put("sortNo", o.getSortNo());
            	    		map.put("isLeaf", false);
            	    		map.put("parentId", "org_"+o.getParentOrg().getId());
            	    		list.add(map);
        				}

        	    		map = new HashMap<>();
        	    		map.put("id", "user_"+user.getId());
        	    		map.put("text", user.getName());
        	    		map.put("sortNo",user.getSortNo());
        	    		map.put("isLeaf", true);
        	    		map.put("parentId", "org_"+o.getId());
        	    		map2.put("href", service+user.getId());
        	    		map3.put("self", map2);
        	    		map.put("_links", map3);
        	    		list.add(map);
        			}else if(level==3){
        				SysOrg po = o.getParentOrg();
        				if(orgIds.indexOf(po.getId()+"#")==-1){
        					orgIds+="org_"+po.getId()+"#";

        					map = new HashMap<>();
            	    		map.put("id", "org_"+po.getId()+"");
            	    		map.put("text", po.getOrgName());
            	    		map.put("sortNo", po.getSortNo());
            	    		map.put("isLeaf", false);
            	    		map.put("parentId", "org_"+org.getId());
            	    		list.add(map);
        				}
        				if(orgIds.indexOf(o.getId()+"#")==-1){
        					orgIds+="org_"+o.getId()+"#";
        					map = new HashMap<>();
            	    		map.put("id", "org_"+o.getId()+"");
            	    		map.put("text", o.getOrgName());
            	    		map.put("sortNo", o.getSortNo());
            	    		map.put("isLeaf", false);
            	    		map.put("parentId", "org_"+po.getId());
            	    		list.add(map);
        				}
        				map = new HashMap<>();
        	    		map.put("id", "user_"+user.getId());
        	    		map.put("text", user.getName());
        	    		map.put("sortNo",user.getSortNo());
        	    		map.put("isLeaf", true);
        	    		map.put("parentId", "org_"+o.getId());
        	    		map2.put("href", service+user.getId());
        	    		map3.put("self", map2);
        	    		map.put("_links", map3);
        	    		list.add(map);
        			}
        		}
        	}
		}
    	map = new HashMap<>();
    	map.put("sysOrgUsers", list);

    	map2.put("_embedded", map);
    	return map2;
    }


	/*
	 * 获取本组织及下级组织id集合
	 */
	@GetMapping("/getSelfAndChildIds")
	public Object getSelfAndChildIds(@RequestParam(value = "id", required = true) Long id){
		ArrayList<Long> ret=new ArrayList<Long>();
		ret= orgService.getSelfAndChildIds(id,ret);
		return ret;
	}

}
